package com.cskaoyan.controller;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.User;
import com.cskaoyan.exception.CustomValidationException;
import com.cskaoyan.util.ValidationUtil;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * @author stone
 * @date 2022/03/26 10:52
 */
@RestController
public class UserController {

    @RequestMapping("login")
    public BaseRespVo login(String username,String password) {
        if (username.length() < 6) {
            return BaseRespVo.fail("长度需要大于等于6");
        }
        if (password.length() < 6) {
            return BaseRespVo.fail("长度需要大于等于6");

        }
        return BaseRespVo.ok();
    }

    @RequestMapping("login2")
    public BaseRespVo login2(@Valid User user,BindingResult bindingResult) {
        //如果其中的一个或多个不符合预期，返回值为true
        //boolean b = bindingResult.hasFieldErrors();
        if (bindingResult.hasFieldErrors()) {//如果有校验错误，才做校验结果的处理
            FieldError fieldError = bindingResult.getFieldError();//拿到参数错误
            String field = fieldError.getField();//成员变量名 → 请求参数名
            Object rejectedValue = fieldError.getRejectedValue(); //传入的错误的值
            String defaultMessage = fieldError.getDefaultMessage();
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("请求参数")
                    .append(field)
                    .append("因为传入了值")
                    .append(rejectedValue)
                    .append("导致异常;")
                    .append(defaultMessage);
            return BaseRespVo.fail(stringBuffer.toString());
        }
        return BaseRespVo.ok();
    }
    @RequestMapping("login3")
    public BaseRespVo login3(@Valid User user,BindingResult bindingResult) {
        //如果其中的一个或多个不符合预期，返回值为true
        //boolean b = bindingResult.hasFieldErrors();
        if (bindingResult.hasFieldErrors()) {//如果有校验错误，才做校验结果的处理
            return ValidationUtil.dealWithValidationResult(bindingResult);
        }
        return BaseRespVo.ok();
    }

    @RequestMapping("login4")
    public BaseRespVo login4(@Valid User user,BindingResult bindingResult) throws CustomValidationException {
        ValidationUtil.validateBindingResult(bindingResult);
        return BaseRespVo.ok();
    }
}
